package cn.hyatt.auth.security.service;

import cn.hyatt.auth.entity.SystemUser;
import cn.hyatt.auth.security.entity.LoginUserDetails;
import cn.hyatt.auth.service.SystemUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 身份验证用户详细信息服务
 *
 * @author hyatt
 */
@Slf4j
@Service
@Primary
@AllArgsConstructor
public class AuthUserDetailsService implements UserDetailsService {

    private SystemUserService systemUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<SystemUser> optional = systemUserService.findByUsername(username);
        SystemUser systemUser = optional.orElseThrow(() -> new UsernameNotFoundException("找不到用户名(" + username + ")的数据"));
        LoginUserDetails userDetails = new LoginUserDetails();
        BeanUtils.copyProperties(systemUser,userDetails);
        return userDetails;
    }
}
